import { Form, Select } from "antd";
import React, { useState } from "react";

export default function EditSelect({
    defaultValue,
    editing = false,
    dataIndex,
    title,
    inputRef,
    save,
    toggleEdit,
    children,
    options = [
        {
            label: "选项1",
            value: '1'
        },
        {
            label: "选项2",
            value: '2'
        }
    ]
}) {

    const getLabel = () => {
        let string = "";
        const index = options.findIndex(item => item.value === defaultValue);
        if (index === -1) {
            return null;
        } else {
            const item = options[index];
            string = item.label;
            return string;
        }


    }
    const [label, setLabel] = useState(getLabel());


    const form = Form.useFormInstance();
    const onChange = (value, options) => {
        form.setFieldValue(dataIndex, value);
        setLabel(options.label);
    }

    return (
        <>
            {
                editing ? <Form.Item
                    style={{
                        margin: 0,
                    }}
                    name={dataIndex}
                    rules={[
                        {
                            required: true,
                            message: ``,
                        },
                    ]}
                    initialValue={defaultValue}
                >
                    <Select
                        ref={inputRef}
                        onBlur={save}
                        options={options}
                        onChange={onChange}
                        style={{
                            width: '100%'
                        }}
                    />
                </Form.Item>
                    :
                    <div
                        className="editable-cell-value-wrap"
                        onClick={toggleEdit}
                    >
                        {label}
                    </div>
            }

        </>
    )
}